﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.Script.Serialization;
using System.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using com.evaair.mall;
using System.Collections.Specialized;

public partial class OrderComplete : System.Web.UI.Page
{
  OrderInfo oi;
  protected void Page_Load(object sender, EventArgs e)
  {
    //購物車為null或是無商品導回首頁
    if (Session["ShoppingCart"] == null || ((ShoppingCart)Session["ShoppingCart"]).GetItemCount()==0)
    {
      Response.Redirect("~/Home.aspx");
    }

    oi = (OrderInfo)Session["OrderInfo"];
    if (!Page.IsPostBack)
    {
      //載入訂單基本資料
      LoadData();
      //載入訂購須知
      LoadShopNode();
    }
  }

  /// <summary>
  /// 設定訂單基本資料
  /// </summary>
  private void LoadData()
  {
    ShoppingCart userShoppingCart = (ShoppingCart)Session["ShoppingCart"];
    if (userShoppingCart != null)
    {
      string strOrderList = CommonUtil.ShoppingCartToOrderListSerialize(userShoppingCart);
      //加贈資料
      List<FreePlusList> liFreePlus = (List<FreePlusList>)Session["FreePlusList"];
      string strFreePlus = liFreePlus.Count > 0 ? JsonConvert.SerializeObject(liFreePlus) : "";
      List<BuyPlusItem> liBuyPlus = (List<BuyPlusItem>)Session["BuyPlusItem"];
      string strBuyPlus = liBuyPlus.Count > 0 ? JsonConvert.SerializeObject(liBuyPlus) : "";
      B2C_MALL_ORDER ws = new B2C_MALL_ORDER();
      ws.Url = ConfigurationManager.AppSettings["B2C_MALL_ORDER"].ToString();
      string strJson = ws.B2C_MALL_ValidateOrderInfo(CommonUtil.GetWebDevice(), oi.MemberID, oi.MemberType,
        oi.DiscType, oi.PayType, strOrderList.ToString(), "", "", "", "", oi.IsLogin, oi.Password, "2", oi.ChooseECouponNo,
        strBuyPlus, strFreePlus, oi.MileMemberID);
      JObject jObj = JsonConvert.DeserializeObject<JObject>(strJson);
      if (jObj["Is_Valid"].ToString() == "Y")
      {
        ltlReceiverName.Text = oi.ReceiverName;
        ltlReceiverPhone.Text = oi.ReceiverPhone;
        //去除與City重複(ex 新竹市)
        string strReceiverArea = (oi.ReceiverCity == oi.ReceiverArea) ? "" : oi.ReceiverArea;
        ltlReceiverAddress.Text = oi.ReceiverZIP + oi.ReceiverCity + strReceiverArea + oi.ReceiverAddress;
        ltlBuyerName.Text = oi.BuyerName;
        ltlBuyerPhone.Text = oi.BuyerPhone;
        //去除與City重複(ex 新竹市)
        string strBuyerArea = (oi.BuyerCity == oi.BuyerArea) ? "" : oi.BuyerArea;
        ltlBuyerAddress.Text = oi.BuyerZIP + oi.BuyerCity + strBuyerArea + oi.BuyerAddress;
        ltlBuyerCompanyTitle.Text = oi.BuyerCompanyTitle;
        ltlBuyerCompanyID.Text = oi.BuyerCompanyID;
        ltlCellPhoneCode.Text = oi.CellPhoneCode;
        ltlCharityCode.Text = oi.CharityCode;
        ltlInvoicePrint.Text = oi.InvoicePrint.Replace("Y", "是").Replace("N", "否");
        ltlInvoicePrintDetail.Text = oi.InvoicePrintDetail.Replace("Y", "是").Replace("N", "否");

        ltlOrderDate.Text = jObj["pOrderDetailList_Ary"]["Order_date"].ToString().Insert(6, "/").Insert(4, "/");
        ltlPayType.Text = oi.PayType.Replace("1", "信用卡").Replace("2", "銀行匯款").Replace("3", "國泰世華銀行ATM");


        var ja = jObj["pOrderSumList_Ary"];
        //總價(折抵後)
        ltlPrice.Text = string.Format("{0:$ #,##0元}", Convert.ToInt32(ja["nTheMoneyWeGet"].ToString()));
        ltlMileSum.Text = string.Format("{0:#,##0}", Convert.ToInt32(ja["mile_Sum"].ToString()));

        if (oi.PayType == "1")
        {
          ltlCreditType.Text = oi.CreditType.Replace("VI", "VISA CARD").Replace("MT", "MASTER CARD")
              .Replace("JC", "JCB").Replace("AX", "AMERICAN EXPRESS").Replace("DC", "DINER CLUB");
          if (oi.CreditNumber.Length > 0)
          {
            ltlCreditNumber.Text = oi.CreditNumber.Substring(0, 4) + " **** **** ";
            ltlCreditNumber.Text += oi.CreditNumber.Substring(12);
            
          }
          //ltlCreditExpire.Text = oi.CreditExpire;
          //ltlAuthCode.Text = oi.AuthCode;
        }
        else
        {
          //信用卡
          trCreditType.Visible = false;
          trCreditNumber.Visible = false;
          //trCreditExpire.Visible = false;
          //trAuthCode.Visible = false;
        }
        //WebATM
        if (oi.PayType == "3")
        {
          tb_atm.Visible = true;
        }
      }
    }
  }



  /// <summary>
  /// 從WS取得訂購須知資料
  /// </summary>
  protected void LoadShopNode()
  {
    B2C_MALL_HOME ws = new B2C_MALL_HOME();
    ws.Url = ConfigurationManager.AppSettings["B2C_MALL_HOME"].ToString();
    string jsonString = ws.B2C_MALL_GetMallOrderShopNote(CommonUtil.GetWebDevice(), User.Identity.Name);
    JObject restoredObject = JsonConvert.DeserializeObject<JObject>(jsonString);
    string Is_Valid = restoredObject["Is_Valid"].ToString();
    string msg = restoredObject["Msg"].ToString();
    if (Is_Valid == "Y")
    {
      dynamic ShopNote = restoredObject["OrderShopNoteAry"];
      ListViewShopNote.DataSource = ShopNote;
      ListViewShopNote.DataBind();
    }
  }

  protected void lbtn_Next_Click(object sender, EventArgs e)
  {
    ShoppingCart userShoppingCart = (ShoppingCart)Session["ShoppingCart"];
    if (userShoppingCart != null)
    {
      //購物車資料
      List<OrderList> liOrderList = new List<OrderList>();
      foreach (CartItem ci in userShoppingCart.CartItems)
      {
        OrderList ol = new OrderList();
        ol.B2C_CODE = ci.B2C_CODE;
        ol.SMAS_CODE = ci.SMAS_CODE;
        ol.Prod_Cat_ID = ci.Prod_Cat_ID;
        ol.QTY = ci.Quantity;
        ol.Type = ci.Type;
        ol.ProdCatID = ci.ProdCatID;
        liOrderList.Add(ol);
      }
      //購物車資料
      string strOrderList = JsonConvert.SerializeObject(liOrderList);
      //加贈資料(無資料傳"")
      List<FreePlusList> liFreePlus = (List<FreePlusList>)Session["FreePlusList"];
      string strFreePlus = CommonUtil.FreePlusListToFreePlusItemSerialize(liFreePlus);
      //加購資料(無資料傳"")
      List<BuyPlusItem> liBuyPlus = (List<BuyPlusItem>)Session["BuyPlusItem"];
      string strBuyPlus = liBuyPlus.Count > 0 ? JsonConvert.SerializeObject(liBuyPlus) : "";

      StringBuilder sbBuyer = new StringBuilder("{");
      sbBuyer.Append("\"BuyerName\":\"" + oi.BuyerName + "\"");
      sbBuyer.Append(",\"BuyerID\":\"" + oi.BuyerID + "\"");
      sbBuyer.Append(",\"BuyerSex\":\"" + oi.BuyerSex + "\"");
      sbBuyer.Append(",\"BuyerBirthday\":\"" + oi.BuyerBirthday + "\"");
      sbBuyer.Append(",\"BuyerPhone\":\"" + oi.BuyerPhone + "\"");
      sbBuyer.Append(",\"Buyer_ZIP\":\"" + oi.BuyerZIP + "\"");
      sbBuyer.Append(",\"Buyer_Address\":\"" + oi.BuyerAddress + "\"");
      sbBuyer.Append(",\"Buyer_Office_Tel\":\"" + oi.BuyerTel + "\"");
      sbBuyer.Append(",\"Buyer_Mobile\":\"" + oi.BuyerMobile + "\"");
      sbBuyer.Append(",\"Buyer_Fax\":\"" + oi.BuyerFax + "\"");
      sbBuyer.Append(",\"Buyer_Email\":\"" + oi.BuyerEamil + "\"");
      sbBuyer.Append(",\"Buyer_SEND_MAIL\":\"" + oi.EDM + "\"}");

      StringBuilder sbReceiver = new StringBuilder("{");
      sbReceiver.Append("\"ReceiverName\":\"" + oi.ReceiverName + "\"");
      sbReceiver.Append(",\"ReceiverPhone\":\"" + oi.ReceiverPhone + "\"");
      sbReceiver.Append(",\"ReceiverSex\":\"" + oi.ReceiverSex + "\"");
      sbReceiver.Append(",\"ReceiverAddress\":\"" + oi.ReceiverAddress + "\"");
      sbReceiver.Append(",\"Receiver_ZIP\":\"" + oi.ReceiverZIP + "\"");
      sbReceiver.Append(",\"Receiver_Office_Tel\":\"" + oi.ReceiverTel + "\"");
      sbReceiver.Append(",\"Receiver_Mobile\":\"" + oi.ReceiverMobile + "\"}");

      StringBuilder sbCreditCard = new StringBuilder("{");
      sbCreditCard.Append("\"creditType\":\"" + oi.CreditType + "\"");
      sbCreditCard.Append(",\"creditNumber\":\"" + oi.CreditNumber + "\"");
      sbCreditCard.Append(",\"creditExpire\":\"" + oi.CreditExpire + "\"");
      sbCreditCard.Append(",\"AuthCode\":\"" + oi.AuthCode + "\"}");

      StringBuilder sbCompany = new StringBuilder("{");
      sbCompany.Append("\"AGREE_DATETIME\":\"" + DateTime.Now.ToString("yyyyMMdd") + "\"");
      sbCompany.Append(",\"INVOICE_PRINT_IND\":\"" + oi.InvoicePrint + "\"");
      sbCompany.Append(",\"PRINT_DETAIL_IND\":\"" + oi.InvoicePrintDetail + "\"");
      sbCompany.Append(",\"CHARITY_CODE\":\"" + oi.CharityCode + "\"");
      sbCompany.Append(",\"CELL_PHONE_CODE\":\"" + oi.CellPhoneCode + "\"");
      sbCompany.Append(",\"BuyerCompanyTitle\":\"" + oi.BuyerCompanyTitle + "\"");
      sbCompany.Append(",\"BuyerCompanyID\":\"" + oi.BuyerCompanyID + "\"");
      sbCompany.Append(",\"Citi_Digi_Certificate\":\"" + oi.CitiDigiCertificate + "\"");
      sbCompany.Append(",\"If_Donate\":\"" + oi.IfDonate + "\"}");

      B2C_MALL_ORDER ws = new B2C_MALL_ORDER();
      ws.Url = ConfigurationManager.AppSettings["B2C_MALL_ORDER"].ToString();
      string strJson = ws.B2C_MALL_ValidateOrderInfo(CommonUtil.GetWebDevice()
          , oi.MemberID, oi.MemberType, oi.DiscType, oi.PayType, strOrderList
          , sbBuyer.ToString(), sbReceiver.ToString(), sbCreditCard.ToString(), sbCompany.ToString()
          , oi.IsLogin, oi.Password, "1", oi.ChooseECouponNo, strBuyPlus, strFreePlus, oi.MileMemberID);

      JObject jObj = JsonConvert.DeserializeObject<JObject>(strJson);
      if (jObj["Is_Valid"].ToString() == "Y")
      {
        dynamic OrderDetail = jObj["pOrderDetailList_Ary"];
        CurrentOrderNo = OrderDetail.Order_No;
        CurrentBuyerName = oi.BuyerName;
        string CurrentGenDate = OrderDetail.Order_date;
        var ja = jObj["pOrderSumList_Ary"];
        //假設是使用WEBATM付款，則交由國泰世華銀行處理資料
        if (oi.PayType == "3")
        {
          NameValueCollection data = new NameValueCollection();
          data.Add("CompanyID", ConfigurationManager.AppSettings["ATMCompanyID"].ToString());
          data.Add("orderNoGenDate", CommonUtil.TransferyyyyMMddToDate(CurrentGenDate));
          data.Add("PtrAcno", jObj["PtrAcno"].ToString());
          data.Add("ItemNo", "");
          data.Add("PurQuantity", "");
          data.Add("amount", ja["nTheMoneyWeGet"].ToString());
          //data.Add("MerchantKey", "");
          HttpHelper.RedirectAndPOST(this.Page,
            "https://www.mybank.com.tw/myatm/Acquiring/AcqOrder_Initial.asp",
            data);
          return;
        }
        //清空購物車
        Session.Remove("ShoppingCart");
        //清空訂單資訊
        Session.Remove("OrderInfo");
        //清空加贈
        Session.Remove("FreePlusItem");
        //清空加購
        Session.Remove("BuyPlusItem");
        //導向訂單完成
        Server.Transfer("~/Orders/ConfirmOrder.aspx");
      }
      else
      {
        //lbl_Error_Message.Text = jObj["Msg"].ToString();
        Page.ClientScript.RegisterStartupScript(this.GetType(),
              "Waring",
              "$('#spanMsg').html('" + jObj["Msg"].ToString() + "');lightbox($('.divMessageLightbox').prop('outerHTML'));",
              true);
      }
    }
  }

  public string CurrentOrderNo { get; set; }
  public string CurrentBuyerName { get; set; }

  //protected void ListViewShopNote_ItemDataBound(object sender, ListViewItemEventArgs e)
  //{
  //  if (e.Item.ItemType == ListViewItemType.DataItem)
  //  {
  //    dynamic note = e.Item.DataItem as dynamic;
  //    (e.Item.FindControl("lbl_Content") as Label).Text = note.Content;   
  //  }
  //}
}